<template>
  <view class="container">
    <!-- 自定义导航栏 -->
    <view class="navbar">
      <view class="navbar-left" @click="goBack">
        <text class="iconfont navbar-icon">&#xe65d;</text>
      </view>
      <text class="navbar-title">地址管理</text>
      <view class="navbar-right" @click="addAddress">
        <text class="add-text">新增</text>
      </view>
    </view>

    <!-- 地址列表 -->
    <view class="address-list" v-if="addressList.length > 0">
      <view 
        v-for="(address, index) in addressList" 
        :key="address.id"
        class="address-item"
        @click="selectAddress(address)"
      >
        <!-- 默认地址标签 -->
        <view v-if="address.isDefault" class="default-badge">默认</view>
        
        <!-- 地址标签 -->
        <view v-if="address.addressLabel" class="address-label">{{ address.addressLabel }}</view>
        
        <!-- 收货人信息 -->
        <view class="receiver-info">
          <text class="receiver-name">{{ address.receiverName }}</text>
          <text class="receiver-phone">{{ address.receiverPhone }}</text>
        </view>
        
        <!-- 地址信息 -->
        <view class="address-info">
          <text class="address-text">{{ address.fullAddress }}</text>
        </view>
        
        <!-- 操作按钮 -->
        <view class="action-buttons">
          <view class="action-btn" @click.stop="editAddress(address)">
            <text class="action-text">编辑</text>
          </view>
          <view v-if="!address.isDefault" class="action-btn" @click.stop="setDefault(address)">
            <text class="action-text">设为默认</text>
          </view>
          <view class="action-btn delete-btn" @click.stop="deleteAddress(address)">
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <view class="empty-icon">📍</view>
      <text class="empty-text">暂无地址信息</text>
      <view class="empty-button" @click="addAddress">
        <text class="empty-button-text">添加地址</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request.js';

export default {
  data() {
    return {
      addressList: [],
      loading: false,
      isSelectMode: false, // 是否为选择模式
    }
  },
  
  onLoad(options) {
    // 检查是否为选择地址模式
    if (options.select === 'true') {
      this.isSelectMode = true;
      uni.setNavigationBarTitle({
        title: '选择地址'
      });
    }
    
    this.loadAddressList();
  },
  
  onShow() {
    // 页面显示时重新加载地址列表
    this.loadAddressList();
  },
  
  methods: {
    // 加载地址列表
    async loadAddressList() {
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        const response = await request({
          url: '/api/address/list',
          method: 'GET'
        });
        
        if (response.code === 200) {
          this.addressList = response.data || [];
        } else {
          uni.showToast({
            title: response.message || '加载地址失败',
            icon: 'error'
          });
        }
      } catch (error) {
        console.error('加载地址列表失败:', error);
        uni.showToast({
          title: '加载地址失败',
          icon: 'error'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 选择地址（选择模式下）
    selectAddress(address) {
      if (this.isSelectMode) {
        // 通过事件总线或页面间通信返回选中的地址
        uni.$emit('addressSelected', address);
        uni.navigateBack();
      }
    },
    
    // 新增地址
    addAddress() {
      uni.navigateTo({
        url: '/pages/address/edit'
      });
    },
    
    // 编辑地址
    editAddress(address) {
      uni.navigateTo({
        url: `/pages/address/edit?id=${address.id}`
      });
    },
    
    // 设为默认地址
    async setDefault(address) {
      try {
        uni.showLoading({
          title: '设置中...'
        });
        
        const response = await request({
          url: `/api/address/set-default/${address.id}`,
          method: 'POST'
        });
        
        if (response.code === 200) {
          uni.showToast({
            title: '设置成功',
            icon: 'success'
          });
          
          // 更新本地数据
          this.addressList.forEach(item => {
            item.isDefault = item.id === address.id;
          });
        } else {
          uni.showToast({
            title: response.message || '设置失败',
            icon: 'error'
          });
        }
      } catch (error) {
        console.error('设置默认地址失败:', error);
        uni.showToast({
          title: '设置失败',
          icon: 'error'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 删除地址
    deleteAddress(address) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个地址吗？',
        success: async (res) => {
          if (res.confirm) {
            await this.confirmDeleteAddress(address);
          }
        }
      });
    },
    
    // 确认删除地址
    async confirmDeleteAddress(address) {
      try {
        uni.showLoading({
          title: '删除中...'
        });
        
        const response = await request({
          url: `/api/address/delete/${address.id}`,
          method: 'POST'
        });
        
        if (response.code === 200) {
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          // 从列表中移除
          const index = this.addressList.findIndex(item => item.id === address.id);
          if (index > -1) {
            this.addressList.splice(index, 1);
          }
        } else {
          uni.showToast({
            title: response.message || '删除失败',
            icon: 'error'
          });
        }
      } catch (error) {
        console.error('删除地址失败:', error);
        uni.showToast({
          title: '删除失败',
          icon: 'error'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack({
        fail: () => {
          uni.switchTab({
            url: '/pages/user/index'
          });
        }
      });
    }
  }
}
</script>

<style scoped>
/* 基本样式 */
.container {
  background: #f5f5f5;
  min-height: 100vh;
}

/* 自定义导航栏 */
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #eee;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-left {
  width: 60px;
}

.navbar-icon {
  font-size: 20px;
  color: #333;
}

.navbar-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.navbar-right {
  width: 60px;
  text-align: right;
}

.add-text {
  color: #667eea;
  font-size: 16px;
}

/* 地址列表 */
.address-list {
  margin-top: 60px;
  padding: 16px;
}

.address-item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
}

.default-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #667eea;
  color: #fff;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.address-label {
  background: #f0f0f0;
  color: #666;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
  margin-bottom: 8px;
}

.receiver-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.receiver-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-right: 12px;
}

.receiver-phone {
  font-size: 14px;
  color: #666;
}

.address-info {
  margin-bottom: 12px;
}

.address-text {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
}

.action-btn:active {
  background: #f8f8f8;
}

.delete-btn {
  border-color: #ff4757;
}

.action-text {
  font-size: 14px;
  color: #333;
}

.delete-btn .action-text {
  color: #ff4757;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  margin-top: 60px;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  color: #999;
  margin-bottom: 30px;
}

.empty-button {
  background: #667eea;
  color: #fff;
  padding: 12px 24px;
  border-radius: 6px;
}

.empty-button:active {
  background: #5a6fd8;
}

.empty-button-text {
  color: #fff;
  font-size: 16px;
}

/* 加载状态 */
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  margin-top: 60px;
}
</style>